package com.srs.util;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.TimerTask;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.srs.action.agent.AgentAction;
import com.srs.dao.UserDao;
import com.srs.dao.agent.ChangeServingCellDao;
import com.srs.dao.agent.LowCsrDao;
import com.srs.dao.agent.NoActivityDao;
import com.srs.dao.agent.NoCallGeneratedDao;
import com.srs.dao.agent.UseWeakRxDao;
import com.srs.dao.agent.UseWeakRxQualityDao;
import com.srs.dao.info.AgentPercentDao;
import com.srs.dao.info.CsrPercentDao;
import com.srs.dao.info.GrxPercentDao;
import com.srs.dao.info.GrxQualityPercentDao;
import com.srs.model.User;

public class MailUtil extends TimerTask{



	private String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

	private String subject;
	private String header;
	private String footer;
	private String sendTime;
	private File file;

	private String host;//SMTP_HOST_NAME;// = "smtp.gmail.com";
	private String account;// = "user";
	private String pass;// = "pass";
	private String port;// = "465";	
	
	// Add List of Email address to who email needs to be sent to
	private String[] emailList = { "vuhoangchienpr@gmail.com" };
	
	

	/* (non-Javadoc)
	 * @see java.util.TimerTask#run()
	 */
	@Override
	public void run() {
		System.out.println("Hello there");
		// TODO Auto-generated method stub
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		HibernateUtil.setSessionFactory(sessionFactory);

		// Get list params
		UserDao userDao = new UserDao();
		List<User> users = userDao.listOpReceiveDailyReport();
		String[] emails = new String[users.size()];
		for(int i=0; i<users.size(); i++){
			emails[i] = users.get(i).getEmail();
		}
		
		System.out.println(emails);
		
		// Get info agent
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");		
		String toDate = dateFormat.format(new Date(new java.util.Date().getTime() - 1000*60*60*24));
		AgentPercentDao agentPercentDao = new AgentPercentDao();
		GrxPercentDao grxPercentDao = new GrxPercentDao();
		GrxQualityPercentDao grxQualityPercentDao = new GrxQualityPercentDao() ;
		CsrPercentDao csrPercentDao = new CsrPercentDao();

		AgentAction agentAction = new AgentAction(); 
		
		// Get AgentInfo
		agentAction.setAgentPercents(agentPercentDao.list(toDate));
		agentAction.setGrxPercents(grxPercentDao.list(toDate));
		agentAction.setGrxQualityPercents(grxQualityPercentDao.list(toDate));
		agentAction.setCsrPercents(csrPercentDao.list(toDate));
		if (agentAction.getAgentPercents()!=null){
			agentAction.setAgentPercent();
		}		
		if (agentAction.getGrxPercents()!=null){
			agentAction.setGrxPercent();
		}
		if (agentAction.getGrxQualityPercents()!=null){
			agentAction.setGrxQualityPercent();
		}
		if (agentAction.getCsrPercents()!=null){
			agentAction.setCsrPercent();
		}
		
		NoActivityDao noActivityDao = new NoActivityDao();
		NoCallGeneratedDao noCallGeneratedDao = new NoCallGeneratedDao();
		ChangeServingCellDao changeServingCellDao = new ChangeServingCellDao();
		UseWeakRxDao useWeakRxDao = new UseWeakRxDao();
		UseWeakRxQualityDao useWeakRxQualityDao = new UseWeakRxQualityDao();
		LowCsrDao lowCsrDao = new LowCsrDao();
		agentAction.setAgentNoActivityNumber(noActivityDao.count(toDate).intValue());
		agentAction.setAgentNoCallGeneratedNumber(noCallGeneratedDao.count(toDate).intValue());
		agentAction.setAgentChangeServingCellNumber(changeServingCellDao.count(toDate).intValue());
		agentAction.setAgentUseWeakRxNumber(useWeakRxDao.count(toDate).intValue());
		agentAction.setAgentUseWeakRxQualityNumber(useWeakRxQualityDao.count(toDate).intValue());
		agentAction.setAgentLowCsrNumber(lowCsrDao.count(toDate).intValue());				
		String message = "<div style=\"width: 740px;margin-top: 80px;\"><div style=\"width: 370px;float: left;\">"+
			"<table class=\"tbl_info\">"+
				"<tr><td class=\"hed\" colspan=\"2\">THÔNG TIN THUÊ BAO TÍNH ĐẾN NGÀY " + toDate + "</td></tr>"+
				"<tr><td>Phần trăm thuê bao đang hoạt động</td>"+
					"<td>" +  agentAction.getAgentPercent().getPercentAgentsActivityStr() + "%</td>"+
				"</tr>"+
				"<tr><td>Phần trăm thuê bao phát sinh cuộc gọi</td>"+
					"<td>" + agentAction.getAgentPercent().getPercentAgentsCallGeneratedStr()  + "%</td>"+
				"</tr>"+
				"<tr><td>Phần trăm thuê bao phát sinh nhiều cuộc gọi</td>"+
					"<td>" + agentAction.getAgentPercent().getPercentAgentsCallGeneratedMoreStr() + "%</td>"+
				"</tr>"+
				"<tr><td>Phần trăm thuê bao thay đổi serving cell</td>"+
					"<td>" + agentAction.getAgentPercent().getPercentAgentsChangeServingCellStr() + "%</td>"+
				"</tr>"+
				"<tr><td>Phần trăm thuê bao activated mới</td>"+
					"<td>" + agentAction.getAgentPercent().getPercentAgentsNewActiveStr() + "%</td>"+
				"</tr>"+
				"<tr><td>Phần trăm thuê bao activate mới phát sinh cuộc gọi </td>"+
					"<td>" + agentAction.getAgentPercent().getPercentAgentsNewCallGeneratedStr() + "%</td>"+
				"</tr>"+
				"<tr><td>Phần trăm số mẫu có cường độ sóng tốt  </td>"+
					"<td>" + agentAction.getGrxPercent().getPercentSamplesGoodStr() + "%</td>"+
				"</tr>"+																								
				"<tr><td>Phần trăm số mẫu có chất lượng sóng tốt </td>"+
					"<td>" + agentAction.getGrxQualityPercent().getPercentSamplesGoodStr() + "%</td>"+
				"</tr>"+									
				"<tr><td>Phần trăm CSR (tỉ lệ cuộc gọi thành công)</td>"+
					"<td>" + agentAction.getCsrPercent().getPercentCallSucceededStr() + "%</td>"+
				"</tr>"+													
			"</table>"+
		"</div>"+
		"<div style=\"width: 370px;float: right;\">"+
			"<table class=\"tbl_info\">"+
				"<tr><td class=\"hed\" colspan=\"2\">CÁC CẢNH BÁO TÍNH ĐẾN NGÀY " + toDate + "</td></tr>"+
				"<tr><td>Số luợng thuê bao không hoạt động</td>"+
					"<td>" + agentAction.getAgentNoActivityNumber() + "</td>"+
				"</tr>"+
				"<tr><td>Số thuê bao đang hoạt động không phát sinh cuộc gọi</td>"+
					"<td>" + agentAction.getAgentNoCallGeneratedNumber() + "</td>"+
				"</tr>"+
				"<tr><td>Số thuê bao thay đổi serving cell</td>"+
					"<td>" + agentAction.getAgentChangeServingCellNumber() + "</td>"+
				"</tr>"+
				"<tr><td>Số thuê bao sử dụng sóng yếu</td>"+
					"<td>" + agentAction.getAgentUseWeakRxNumber() + "</td>"+
				"</tr>"+
				"<tr><td>Số thuê bao có tỉ lệ CSR thấp</td>"+
					"<td>" + agentAction.getAgentLowCsrNumber() + "</td>"+
				"</tr>"+									
				"<tr><td>Số thuê bao sử dụng sóng chất chất lượng tồi</td>"+
					"<td>" + agentAction.getAgentUseWeakRxQualityNumber() + "</td>"+
				"</tr>"+													
			"</table>"+
		"</div></div>";
		
		this.postMail(emails, message);			
	}

	public MailUtil(File file) {
			this.file = file;
	}

	public void getConfig(){
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(this.file);
			doc.getDocumentElement().normalize();
//			System.out.println("Root element "
//					+ doc.getDocumentElement().getNodeName());
			NodeList nodeLst = doc.getElementsByTagName("mail");
//			System.out.println("Information of all employees");

			for (int s = 0; s < nodeLst.getLength(); s++) {

				Node fstNode = nodeLst.item(s);

				if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

					Element mail = (Element) fstNode;

					NodeList subjectList = mail.getElementsByTagName("subject");
					Element subjectElement = (Element) subjectList.item(0);
					NodeList subjectNoteList = subjectElement.getChildNodes();
//					System.out.println("Subject : "
//							+ ((Node) subjectNoteList.item(0)).getNodeValue());
					this.setSubject(((Node) subjectNoteList.item(0))
							.getNodeValue());

					NodeList headerList = mail.getElementsByTagName("header");
					Element headerElement = (Element) headerList.item(0);
					NodeList headerNoteList = headerElement.getChildNodes();
//					System.out.println("Header : "
//							+ ((Node) headerNoteList.item(0)).getNodeValue());
					this.setHeader(((Node) headerNoteList.item(0))
							.getNodeValue());

					NodeList footerList = mail.getElementsByTagName("footer");
					Element footerElement = (Element) footerList.item(0);
					NodeList footerNoteList = footerElement.getChildNodes();
//					System.out.println("Footer : "
//							+ ((Node) footerNoteList.item(0)).getNodeValue());
					this.setFooter(((Node) footerNoteList.item(0))
							.getNodeValue());

					NodeList sendTimeList = mail.getElementsByTagName("time");
					Element sendTimeElement = (Element) sendTimeList.item(0);
					NodeList sendTimeNoteList = sendTimeElement.getChildNodes();
//					System.out.println("Send time : "
//							+ ((Node) sendTimeNoteList.item(0)).getNodeValue());
					this.setSendTime(((Node) sendTimeNoteList.item(0))
							.getNodeValue());
					
					NodeList accountList = mail.getElementsByTagName("account");
					Element accountElement = (Element) accountList.item(0);
					NodeList accountNoteList = accountElement.getChildNodes();
//					System.out.println("Account : "
//							+ ((Node) accountNoteList.item(0)).getNodeValue());
					this.setAccount(((Node) accountNoteList.item(0))
							.getNodeValue());
										
					NodeList passList = mail.getElementsByTagName("pass");
					Element passElement = (Element) passList.item(0);
					NodeList passNoteList = passElement.getChildNodes();
//					System.out.println("pass : "
//							+ ((Node) passNoteList.item(0)).getNodeValue());
					this.setPass(((Node) passNoteList.item(0))
							.getNodeValue());

					NodeList hostList = mail.getElementsByTagName("host");
					Element hostElement = (Element) hostList.item(0);
					NodeList hostNoteList = hostElement.getChildNodes();
//					System.out.println("host : "
//							+ ((Node) hostNoteList.item(0)).getNodeValue());
					this.setHost(((Node) hostNoteList.item(0))
							.getNodeValue());		

					NodeList portList = mail.getElementsByTagName("port");
					Element portElement = (Element) portList.item(0);
					NodeList portNoteList = portElement.getChildNodes();
//					System.out.println("port : "
//							+ ((Node) portNoteList.item(0)).getNodeValue());
					this.setPort(((Node) portNoteList.item(0))
							.getNodeValue());						
				}

			}
		} catch (Exception e) {
//			e.printStackTrace();
		}		
	}
	
	public void postMail(String recipients[], String message) {

		boolean debug = false;

		try {
			// Set the host smtp address
			Properties props = new Properties();
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.auth", "true");

			props.put("mail.debug", "true");
			props.put("mail.smtp.port", port);
			props.put("mail.smtp.socketFactory.port", port);
			props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
			props.put("mail.smtp.socketFactory.fallback", "false");

			Authenticator auth = new SMTPAuthenticator();
			Session session = Session.getDefaultInstance(props, auth);

			session.setDebug(debug);

			// create a message
			Message msg = new MimeMessage(session);

			// set the from and to address
			InternetAddress addressFrom = new InternetAddress(this.account);
			msg.setFrom(addressFrom);

			// Setting the Subject and Content Type
			msg.setSubject(this.subject);
			msg.setContent(this.header + "<br/>" + message + "<br/>"
					+ this.footer, "text/html");
			
//			InternetAddress[] addressTo = new InternetAddress[recipients.length];
			for (int i = 0; i < recipients.length; i++) {
				try{
					InternetAddress[] to = new InternetAddress[1];
					to[0] = new InternetAddress(recipients[i]);
					msg.setRecipients(Message.RecipientType.TO, to);
					Transport.send(msg);
//					System.out.println("Send email to: " + recipients[i]);					
				}catch (Exception e) {
//					System.out.println("Error send mail: " + e.getMessage());
				}
//				addressTo[i] = new InternetAddress(recipients[i]);
			}
			


		} catch (Exception e) {
//			System.out.println(e.toString());
		}
	}

	/**
	 * SimpleAuthenticator is used to do simple authentication when the SMTP
	 * server requires it.
	 */
	private class SMTPAuthenticator extends javax.mail.Authenticator {

		public PasswordAuthentication getPasswordAuthentication() {
			String username = account;
			String password = pass;
			return new PasswordAuthentication(username, password);
		}
	}

	/**
	 * @return the subject
	 */
	public String getSubject() {
		return subject;
	}

	/**
	 * @param subject
	 *            the subject to set
	 */
	public void setSubject(String subject) {
		this.subject = subject;
	}

	/**
	 * @return the header
	 */
	public String getHeader() {
		return header;
	}

	/**
	 * @param header
	 *            the header to set
	 */
	public void setHeader(String header) {
		this.header = header;
	}

	/**
	 * @return the footer
	 */
	public String getFooter() {
		return footer;
	}

	/**
	 * @param footer
	 *            the footer to set
	 */
	public void setFooter(String footer) {
		this.footer = footer;
	}

	/**
	 * @return the sendTime
	 */
	public String getSendTime() {
		return sendTime;
	}

	/**
	 * @param sendTime
	 *            the sendTime to set
	 */
	public void setSendTime(String sendTime) {
		this.sendTime = sendTime;
	}

	/**
	 * @return the file
	 */
	public File getFile() {
		return file;
	}

	/**
	 * @param file the file to set
	 */
	public void setFile(File file) {
		this.file = file;
	}

	/**
	 * @return the host
	 */
	public String getHost() {
		return host;
	}

	/**
	 * @param host the host to set
	 */
	public void setHost(String host) {
		this.host = host;
	}

	/**
	 * @return the account
	 */
	public String getAccount() {
		return account;
	}

	/**
	 * @param account the account to set
	 */
	public void setAccount(String account) {
		this.account = account;
	}

	/**
	 * @return the pass
	 */
	public String getPass() {
		return pass;
	}

	/**
	 * @param pass the pass to set
	 */
	public void setPass(String pass) {
		this.pass = pass;
	}

	/**
	 * @return the port
	 */
	public String getPort() {
		return port;
	}

	/**
	 * @param port the port to set
	 */
	public void setPort(String port) {
		this.port = port;
	}

	/**
	 * @return the emailList
	 */
	public String[] getEmailList() {
		return emailList;
	}

	/**
	 * @param emailList the emailList to set
	 */
	public void setEmailList(String[] emailList) {
		this.emailList = emailList;
	}

}
